package controllers.root;

import java.util.ArrayList;
import java.util.List;
import siena.Model;
import utils.json.ResidenceJSON;
import utils.json.UserResidenceJSON;
import com.google.appengine.api.NamespaceManager;
import com.google.gson.JsonObject;
import exceptions.ValidationException;

public class ResidenceController extends BaseRootController {

	public static void save(Long id, JsonObject body) throws ValidationException {
		
		/*ResidenceJSON residenceJSON = new ResidenceJSON(body); 
		Residence residence = residenceJSON.getResidence();
		
		if(id == null) { // At this point can not come admin user data
			validation.valid(residence);
			if(validation.hasErrors()) {
				throw new ValidationException(validation.errors());
			} else {
				residence.active = Boolean.TRUE;
				residence.save();
				renderJSON(new ResidenceJSON(residence));
			}
		} else {
			UserResidenceJSON adminJSON = residenceJSON.getAdmin();
			InternshipUser admin = adminJSON.getUser();
			admin.admin = Boolean.TRUE; //INFO  Using this method the user will be an admin
			admin.setAccess(Boolean.TRUE); //TODO!!!!
			
			// Change namespace to save the user
			String oldNamespace = NamespaceManager.get();
			try {
				NamespaceManager.set(String.valueOf(residence.id));
				
				if(admin.getId() != null) {
					// Its an update. Retrieve the old user and update it
					InternshipUser oldUser = InternshipUser.getById(admin.getId());
					// Check if the password was updated!
					if(admin.password == null || ("").equals(admin.password)) {
						// We have to use the oldpass
						admin.password = oldUser.password;
					} 
					oldUser.password = admin.password;
					oldUser.username = admin.username;
					oldUser.setAccess(admin.getAccess());
					oldUser.admin = admin.admin;
					admin = oldUser;
				}
					
				validation.valid(admin);
				if(validation.hasErrors()) {
					throw new ValidationException(validation.errors());
				}
				admin.save();
				ok();
			} catch(Exception e) {
				error();
			} finally {
				NamespaceManager.set(oldNamespace);
			}
			
		}*/
	}
	
	
	
	public static void delete(Long id) {
		/*Residence residence = Residence.getById(id);
		residence.delete();*/
		ok();
	}
	
	public static void detail(Long id) {
		/*Residence residence = Residence.getById(id);
		
		renderJSON(new ResidenceJSON(residence));*/
	}
	
	public static void list() {
		/*List<Residence> residences = Model.all(Residence.class).fetch();
		ArrayList<ResidenceJSON> residencesJSON = new ArrayList<ResidenceJSON>();
		if(residences != null) {
			for(Residence residence : residences) {
				residencesJSON.add(new ResidenceJSON(residence));
			}
		}
		renderJSON(residencesJSON);*/
	}
}
